package com.mazong.serversecbasic.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class MyAccessDecisionManager implements AccessDecisionManager {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if(null == collection || collection.size()<=0) {
            log.info("decide,no role...");
            return;
        }

        String needRole;
        for(ConfigAttribute configAttribute:collection) {
            needRole = configAttribute.getAttribute();
            for(GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                log.info("myrole={},needrole={}", grantedAuthority.getAuthority(),needRole);
                if(needRole.trim().equals(grantedAuthority.getAuthority().trim())) {
                    log.info("decide,role OK");
                    return;
                }
            }
        }

        throw new AccessDeniedException("没有访问当前页面的权限");
    }
}
